﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BotvaBot.RequestChains;
using HttpRequester.RequestMakers.Base;
using HttpRequester;
using Helpers;
using mshtml;
using BotvaBot.RequestChainItems.Base;
using Common.Constants;
using BotvaBot.BusinessLayer.RequestChainItems.Factory;

namespace BotvaBot.RequestChainItems
{
    [ChainItem]
    public class SendBoatChainItem : BotvaLogedInChainItemBase
    {
        [ValidatePageTitle(Title = "Причал. Ботва Онлайн | Битва за реальную капусту!")]
        protected override bool IsContextValidInternal()
        {
            return base.IsContextValidInternal();
        }

        protected override void PrepareRequestInternal()
        {
            Url = "http://g3.botva.ru/harbour.php";
            Method = HttpMethod.POST;
            AddGet("a", "pier");

            string content = Chain.LastContent;
            content = content.Replace(Environment.NewLine, string.Empty);
            while (content.IndexOf("  ") >= 0)
            {
                content = content.Replace("  ", " ");
            }
            content = content.ToUpper();

            IHTMLDocument2 html = new HTMLDocumentClass();
            html.write(content);
            html.close();

            IHTMLElementCollection all = html.body.all as IHTMLElementCollection;

            string s = "";
            foreach (IHTMLElement item in all)
            {
                if (item.tagName.ToUpper() != "FORM")
                    continue;

                if (item.getAttribute("action", 0).ToString() != "HARBOUR.PHP?A=PIER")
                    continue;

                IHTMLElementCollection inputs = (item.children as IHTMLElementCollection).tags("INPUT") as IHTMLElementCollection;
                foreach (IHTMLElement input in inputs)
                {
                    if (input.getAttribute("NAME", 0) == null || input.getAttribute("VALUE", 0) == null)
                        continue;

                    AddPost(input.getAttribute("NAME", 0).ToString().ToLower(), input.getAttribute("VALUE", 0).ToString().ToLower());
                }
            }

            AddPost("submit", "ОТПРАВИТЬ");
        }

        public override bool IsResponseValidInternal()
        {
            //string content = Requester.PageContent;
            //content = content.Replace(" ", string.Empty)
            //                .Replace("'", "\"")
            //                .ToUpper();

            //string searchedStr = "<input type='submit' class='cmd_all cmd_medium_sl cmd_amedium_sl ' value='ВХОД' >";
            //searchedStr = searchedStr.Replace(" ", string.Empty)
            //                .Replace("'", "\"")
            //                .ToUpper();

            //return content.Contains(searchedStr);

            return true;
        }
    }
}
